//
//  ARTWatchHistoryDailyController.m
//  ChartsDemo
//
//  Created by yunda on 2021/10/13.
//

#import "ARTWatchHistoryDailyController.h"
// views
#import "ARTWatchHistoryDailyTopView.h"
#import "ARTWatchHistoryDailySpoView.h"
#import "ARTWatchHistoryCommonValueView.h"
#import "ARTWatchHistoryDailyPrView.h"
#import "CircleView.h"

@interface ARTWatchHistoryDailyController ()

// scrollView
@property (strong, nonatomic)  YDHBaseScrollView *scrollView;
// 提示视图
@property (strong, nonatomic)  ARTWatchHistoryDailyTopView *topView;
// ARTWatchHistoryDailySpoView
@property (strong, nonatomic)  ARTWatchHistoryDailySpoView *spoChartView;
// ARTWatchHistoryCommonValueView
@property (strong, nonatomic)  ARTWatchHistoryCommonValueView *spoView;
// ARTWatchHistoryDailyPrView
@property (strong, nonatomic)  ARTWatchHistoryDailyPrView *prChartView;
// ARTWatchHistoryCommonValueView
@property (strong, nonatomic)  ARTWatchHistoryCommonValueView *prView;

@property (strong, nonatomic)  UIButton *rightButton;

@end

@implementation ARTWatchHistoryDailyController

#pragma mark--THE LIFE CYCLE
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    J_Add_Notify(self, @selector(refreshLanguage), ART_Notify_LanguageChanged, nil);
    [self refreshLanguage];
    NSLog(@"日常报告模型数据receiveModel=%@",[_receiveModel modelToJSONString]);
}

- (void)initSubviews{
    [super initSubviews];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
    
    [self.view addSubview:self.scrollView];
    
    [_scrollView appendOneItemView:self.topView];
    [_scrollView appendOneItemView:self.spoChartView];
    [_scrollView appendOneItemView:self.spoView];
    [_scrollView appendOneItemView:self.prChartView];
    [_scrollView appendOneItemView:self.prView];
    
    YDHBaseItemView *tempView = [[YDHBaseItemView alloc]initWithFrame:J_Frame(0, 0, J_SCREEN_WIDTH, J_TabBarHeight+10)];
    tempView.backgroundColor = _scrollView.backgroundColor;
    [_scrollView appendOneItemView:tempView];
    
    NSArray *datasList = @[];
    NSString *filePath = [J_Path_Document stringByAppendingPathComponent:@"watchHistory"];
    NSString *watchPath = [filePath stringByAppendingPathComponent:_receiveModel.dataFileName];
    NSString *jsonString = [NSString stringWithContentsOfFile:watchPath encoding:NSUTF8StringEncoding error:nil];
    if (jsonString) {
        jsonString = [RSAEncryptor decryptSubsectionString:jsonString privateKey:ART_Prikey];
        datasList = [NSArray modelArrayWithClass:[ARTWathDataModel class] json:jsonString];
    }
    NSLog(@"日常报告模型数据datasList=%@",datasList);
    
    [self configureTopView:datasList];
    [self configureOximiter:datasList];
    [self configureHeartRate:datasList];
}

- (void)dealloc{
    J_Remove_Notify(self);
}

#pragma mark--PRIVATE METHOD
- (void)configureTopView:(NSArray *)datasList{
    NSString *date = _receiveModel.date;
    if ([date containsString:@" "]) {
        date = [date componentsSeparatedByString:@" "].firstObject;
    }
    _topView.dateLabel.text = date;
    
    NSInteger _spo2_L = 0;
    NSInteger _pr_H = 0;
    NSInteger _pr_L = 0;
    for (ARTWathDataModel *data in datasList) {
        if (data.spo2 < 95 && data.spo2 !=0) {
            _spo2_L++;
        }
        if (data.pr >= 101) {
            _pr_H++;
        }
        if (data.pr <= 59 && data.pr != 0) {
            _pr_L++;
        }   
    }
    _topView.alertLabel.text = FYLocalizedString(@"oxygen_healthy", @"");
    _topView.alertLabel.textColor = [UIColor colorWithString:@"#0DA462"];
    _spoChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_normal", @"");
    _prChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_normal", @"");
    _spoChartView.titleView.detailLabel.textColor = _prChartView.titleView.detailLabel.textColor = _topView.alertLabel.textColor;
    if (_pr_L >= 1 && _spo2_L >= 1) {
        _topView.alertLabel.text = FYLocalizedString(@"oxygen_heart_low_ox_low", @"");
        _topView.alertLabel.textColor = [UIColor colorWithString:@"#E50C0C"];
        _spoChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_low", @"");
        _prChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_low", @"");
        _spoChartView.titleView.detailLabel.textColor = _prChartView.titleView.detailLabel.textColor = _topView.alertLabel.textColor;
        return;
    }
    if (_pr_H >= 1 && _spo2_L >= 1) {
        _topView.alertLabel.text = FYLocalizedString(@"oxygen_heart_high_ox_low", @"");
        _topView.alertLabel.textColor = [UIColor colorWithString:@"#E50C0C"];
        _spoChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_low", @"");
        _prChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_high", @"");
        _spoChartView.titleView.detailLabel.textColor = _prChartView.titleView.detailLabel.textColor = _topView.alertLabel.textColor;
        return;
    }
    if (_spo2_L >= 1) {
        _topView.alertLabel.text = FYLocalizedString(@"oxygen_ox_low", @"");
        _topView.alertLabel.textColor = [UIColor colorWithString:@"#E50C0C"];//[UIColor colorWithString:@"#FF9627"];
        _spoChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_low", @"");
        _spoChartView.titleView.detailLabel.textColor = _topView.alertLabel.textColor;
        return;
    }
    if(_pr_H >= 1){
        _topView.alertLabel.text = FYLocalizedString(@"oxygen_heart_high", @"");
        _topView.alertLabel.textColor = [UIColor colorWithString:@"#E50C0C"];
        _prChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_high", @"");
        _prChartView.titleView.detailLabel.textColor = _topView.alertLabel.textColor;
        return;
    }
    if(_pr_L >= 1){
        _topView.alertLabel.text = FYLocalizedString(@"oxygen_heart_low", @"");
        _topView.alertLabel.textColor = [UIColor colorWithString:@"#E50C0C"];
        _prChartView.titleView.detailLabel.text = FYLocalizedString(@"oxygen_low", @"");
        _prChartView.titleView.detailLabel.textColor = _topView.alertLabel.textColor;
        return;
    }
}

- (NSArray *)timeTitleArray{
    long duration = _receiveModel.longTime/3;
    NSDate *startData = [NSDate j_dateWithString:_receiveModel.date format:@"yyyy/MM/dd HH:mm:ss"];
    NSDate *date2 = [startData j_dateByAddingSeconds:duration];
    NSDate *date3 = [startData j_dateByAddingSeconds:duration*2];
    NSDate *endDate = [startData j_dateByAddingSeconds:_receiveModel.longTime];
    NSString *string1 = [startData j_stringWithFormat:@"HH:mm:ss"];
    NSString *string2 = [date2 j_stringWithFormat:@"HH:mm:ss"];
    NSString *string3 = [date3 j_stringWithFormat:@"HH:mm:ss"];
    NSString *string4 = [endDate j_stringWithFormat:@"HH:mm:ss"];
    return @[SAFE_STRING(string4),SAFE_STRING(string3),SAFE_STRING(string2),SAFE_STRING(string1)];
}

- (void)configureOximiter:(NSArray *)datasList{
    _spoChartView.titleView.titleLabel.text = [NSString stringWithFormat:@"%@(%@)",FYLocalizedString(@"oxygen_warning_sp_n", @""),@"%"];
    _spoChartView.titleView.helpButton.hidden = YES;
    // 绘制血氧饱和度图
    _spoChartView.chartView.yLabelArray = @[
        @"70",
        @"80",
        @"90",
        @"100"
    ];
    
    _spoChartView.chartView.xLabelArray = [self timeTitleArray];
    NSMutableArray *dataSets = [NSMutableArray array];
    for (ARTWathDataModel *temp in datasList) {
        [dataSets addObject:@(temp.spo2)];
    }
    _spoChartView.chartView.valueArray = dataSets;
    [_spoChartView.chartView startDrawing3];
//    _spoChartView.chartView.valueArray = dataSets;
//    _spoChartView.chartView.maxValue = 100;
//    _spoChartView.chartView.minValue = 70;
//    _spoChartView.chartView.canSkip = YES;
//    _spoChartView.chartView.skip_max = 100;
//    _spoChartView.chartView.skip_min = 70;
//    [_spoChartView.chartView startDrawing];
    
    _spoView.value1Label.attributedText = [_spoView attributeTextWithValue:@(_receiveModel.spo2Max).stringValue valueColor:[CircleView spoColor:_receiveModel.spo2Max] unit:@"%" message:[self filterTitle:FYLocalizedString(@"oxygen_max_value", @"")]];
    _spoView.value2Label.attributedText = [_spoView attributeTextWithValue:@(_receiveModel.spo2Avg).stringValue valueColor:[CircleView spoColor:_receiveModel.spo2Avg] unit:@"%" message:[self filterTitle:FYLocalizedString(@"oxygen_average_value", @"")]];
    _spoView.value3Label.attributedText = [_spoView attributeTextWithValue:@(_receiveModel.spo2Min).stringValue valueColor:[CircleView spoColor:_receiveModel.spo2Min] unit:@"%" message:[self filterTitle:FYLocalizedString(@"oxygen_mini_value", @"")]];
}

- (void)configureHeartRate:(NSArray *)datasList{
    _prChartView.titleView.titleLabel.text = FYLocalizedString(@"sleep_watch_resting", @"");
    _prChartView.titleView.helpButton.hidden = YES;
    // 绘制心率图
    _prChartView.chartView.yLabelArray = @[
        @"0",
        @"50",
        @"100",
        @"150",
        @"200",
        @"250"
    ];
    
    _prChartView.chartView.xLabelArray = [self timeTitleArray];
    NSMutableArray *dataSets = [NSMutableArray array];
    for (ARTWathDataModel *temp in datasList) {
        [dataSets addObject:@(temp.pr)];
    }
    _prChartView.chartView.valueArray = dataSets;
    _prChartView.chartView.maxValue = 250;
    _prChartView.chartView.minValue = 0;
    _prChartView.chartView.canSkip = YES;
    _prChartView.chartView.skip_max = 250;
    _prChartView.chartView.skip_min = 15;
    [_prChartView.chartView startDrawing];
    
    _prView.value1Label.attributedText = [_prView attributeTextWithValue:@(_receiveModel.prMax).stringValue valueColor:[CircleView prColor:_receiveModel.prMax] unit:@"" message:[self filterTitle:FYLocalizedString(@"oxygen_heart_max_value", @"")]];
    _prView.value2Label.attributedText = [_prView attributeTextWithValue:@(_receiveModel.prAvg).stringValue valueColor:[CircleView prColor:_receiveModel.prAvg] unit:@"" message:[self filterTitle:FYLocalizedString(@"oxygen_heart_average_value", @"")]];
    _prView.value3Label.attributedText = [_prView attributeTextWithValue:@(_receiveModel.prMin).stringValue valueColor:[CircleView prColor:_receiveModel.prMin] unit:@"" message:[self filterTitle:FYLocalizedString(@"oxygen_heart_mini_value", @"")]];
}

- (NSString *)filterTitle:(NSString *)title{
    if ([title containsString:@"："]) {
        title = [title stringByReplacingOccurrencesOfString:@"：" withString:@""];
    }
    if ([title containsString:@":"]) {
        title = [title stringByReplacingOccurrencesOfString:@":" withString:@""];
    }
    return title;
}

#pragma mark--TARGET ACTION
- (void)refreshLanguage{
    self.title = FYLocalizedString(@"sleep_watch_daily_test_report", @"");
}

- (void)rightAction{
//    _scrollView.contentOffset = CGPointZero;
//    [_scrollView scrollsToTop];
    UIImage *image = [_scrollView qmui_snapshotLayerImage];//[_scrollView snapshot]
    if (!image) {
        [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
        return;
    }
    // 分享的图片
    UIImage *imageToShare = image;
    NSArray *activityItems = @[imageToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    // 不出现在活动项目
//        activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    J_WeakSelf(activityVC)
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        J_StrongSelf(activityVC)
        if (completed) {
            // 分享成功
            [activityVC dismissViewControllerAnimated:YES completion:nil];
//            [self.navigationController popViewControllerAnimated:NO];
//                [ARTNavigation closeViewControllerAnimated:NO];
            if (activityError) {
                [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
            }else{
                [QMUITips showWithText:FYLocalizedString(@"share_success", @"")];
            }
        } else  {
            NSLog(@"cancled");
            //分享 取消
            [activityVC dismissViewControllerAnimated:YES completion:nil];
//            [self.navigationController popViewControllerAnimated:NO];
//                [ARTNavigation closeViewControllerAnimated:NO];
            [QMUITips showWithText:FYLocalizedString(@"share_cancel", @"")];
        }
    };
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--Getter
- (YDHBaseScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[YDHBaseScrollView alloc]init];
        _scrollView.frame = CGRectMake(0, J_NavBarHeight, J_SCREEN_WIDTH, J_SCREEN_HEIGHT-J_NavBarHeight);
        _scrollView.backgroundColor = J_ColorFromHEX(0xF5F5F5);
        _scrollView.bounces = YES;
//        _scrollView.margin_bottom = 70;
    }
    return _scrollView;
}

- (ARTWatchHistoryDailyTopView *)topView{
    if (!_topView) {
        _topView = [[ARTWatchHistoryDailyTopView alloc]init];
    }
    return _topView;
}

- (ARTWatchHistoryDailySpoView *)spoChartView{
    if (!_spoChartView) {
        _spoChartView = [[ARTWatchHistoryDailySpoView alloc]init];
    }
    return _spoChartView;
}

- (ARTWatchHistoryCommonValueView *)spoView{
    if (!_spoView) {
        _spoView = [[ARTWatchHistoryCommonValueView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 88)];
        _spoView.margin_top = 10;
    }
    return _spoView;
}

- (ARTWatchHistoryDailyPrView *)prChartView{
    if (!_prChartView) {
        _prChartView = [[ARTWatchHistoryDailyPrView alloc]init];
        _prChartView.margin_top = 10;
    }
    return _prChartView;
}

- (ARTWatchHistoryCommonValueView *)prView{
    if (!_prView) {
        _prView = [[ARTWatchHistoryCommonValueView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 88)];
        _prView.margin_top = 10;
    }
    return _prView;
}

- (UIButton *)rightButton{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = J_FrameWithSize(40, 40);
        [_rightButton setImage:J_ImageNamed(@"nav_ic_share1") forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

@end
